package ch.ethz.fcl.metrobuzz.render.accessbility;

import java.util.List;

import org.lwjgl.opengl.GL11;

import ch.ethz.fcl.metrobuzz.MBContainer;
import ch.ethz.fcl.metrobuzz.controller.external.ActionEvent;
import ch.ethz.fcl.metrobuzz.data.accessibility.activity.PointOfInterest;
import ch.ethz.fcl.metrobuzz.data.transit.Stop;
import ch.ethz.fcl.metrobuzz.spatialindex.object2d.Point2D;
import ch.ethz.fcl.metrobuzz.spatialindex.object3d.Point3D;
import ch.ethz.fcl.metrobuzz.tools.MBGL;
import ch.ethz.fcl.metrobuzz.tools.MBTools;

public class ActivityDebug {
	private MBContainer container;

	private List<PointOfInterest> workActivities;
	private PointOfInterest selectedWork;

	public ActivityDebug(MBContainer container) {
		this.container = container;
		workActivities = container.getData().getActivity().getWork();
	}

	public void render() {
		MBGL.enableBlend();
		if (selectedWork != null) {
			GL11.glPointSize(5);
			GL11.glBegin(GL11.GL_POINTS);
			GL11.glColor4f(0, 1, 0, 1.0f);
			GL11.glVertex2f(selectedWork.getX(), selectedWork.getY());

			GL11.glColor4f(1, 0, 0, 1.0f);
			for (Stop stop : selectedWork.getNearbyStops())
				GL11.glVertex2f(stop.getX(), stop.getY());
			GL11.glEnd();
		}
		MBGL.disableBlend();
	}

	public void handleActionEvent() {
		if (workActivities == null)
			workActivities = container.getData().getActivity().getWork();

		ActionEvent action = container.getControl().getTuioListener()
				.getTuioEvent();
		if (action == null)
			action = container.getControl().getMouseListener().getRightMouse();

		if (action != null) {
			Point3D event = container
					.getViewer()
					.getProjection()
					.getWorldCoord(
							new Point2D(action.getEventX(), action.getEventY()),
							0);
			if (action.getAction() == ActionEvent.ACTION_DOWN) {
				float minDist = Float.MAX_VALUE;

				for (PointOfInterest work : workActivities) {
					float distance = MBTools.distance(work.getX(), work.getY(),
							event.getX(), event.getY());
					if (distance < minDist) {
						minDist = distance;
						selectedWork = work;
					}
				}
			}
		}
	}
}
